<script setup lang="ts">
import { onMounted, ref } from 'vue';

import { useUserStore } from '@vben/stores';

import { useFs } from '@fast-crud/fast-crud';
import { Button } from 'ant-design-vue';

import { UserConfig } from '#/api';
import { getValidateRulesByFs } from '#/api/common/validateByFs';
import { ActionEnum } from '#/enums/commonEnum';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';
import { useAuthStore } from '#/store';

import { createCrudOptions, frontRules } from '../data/base-setting-crud';

const formRef = ref();
const { crudBinding, appendCrudOptions } = useFs({ createCrudOptions });
const buttonLoading = ref(false);
const { createMessage } = useMessage();
const userStore = useUserStore();
const authStore = useAuthStore();

onMounted(async () => {
  const data = userStore.userInfo;

  formRef.value.setFormData(
    { ...data, logo: data?.avatarId },
    { mergeForm: false },
  );

  const addFormOptions = await getValidateRulesByFs({
    Api: UserConfig.UpdateBaseInfo,
    mode: ActionEnum.ADD,
    customRules: frontRules(formRef),
    trigger: 'change',
  });
  appendCrudOptions({ ...addFormOptions });
});

async function formSubmit() {
  buttonLoading.value = true;
  try {
    await formRef.value.submit();
    createMessage.success($t(`common.tips.updateSuccess`));
    authStore.fetchUserInfo();
  } finally {
    buttonLoading.value = false;
  }
}
</script>

<template>
  <div>
    <FsForm ref="formRef" v-bind="crudBinding.addForm" />
    <div style="margin-top: 10px">
      <Button
        v-if="formRef"
        type="primary"
        :loading="buttonLoading"
        @click="formSubmit"
      >
        修改
      </Button>
    </div>
  </div>
</template>
